import React, { useState, useEffect, useRef } from 'react';
import { Grid, Input, Card, Tag, Button, Empty, Tabs, Typography } from '@arco-design/web-react';
import { IconRightCircle, IconCloseCircle } from '@arco-design/web-react/icon';
import { IconSearch, IconLoop } from '@arco-design/web-react/icon';
import styles from './style/index.module.less';
import { Pagination } from '@arco-design/web-react';
const TabPane = Tabs.TabPane;


const Row = Grid.Row;
const Col = Grid.Col;
const InputSearch = Input.Search;

import {
    searchCourse,
    getChapterBySchCourseId,
    getSchCourseKnowledgeBySchCourseChapterId,
    getSchCourseResourceBySchCourseKnowledgeId,
    getLessonsByPageApi,
    searchCourseChapter,
    searchCourseKnowledge,
    searchCourseResource
} from '@/request/api';

import DetailDrawer from "@/pages/knowledgeCheck/list/DetailDrawer";
function KnowledgeCheck() {
    const [inputValue, setInputValue] = useState('');
    // 初始page方便重置增加数据同步维护
    const initPage = {
        pageNum: 1,
        pageSize: 18,
        name: "",
        range: "",
        refMajors: "",
        required: "",
    }
    const [page, setPage] = useState({
        pageNum: 1,
        pageSize: 18,
        name: "",
        range: "",
        refMajors: "",
        required: "",
    })
    //详情抽屉
    const detailRef = useRef(null)
    const [courses, setCourses] = useState({
        total: 0,
        list: [],
    });
    //子页面左侧菜单
    const [leftMenu, setLeftMenu] = useState([])


    // 初始化调用 模拟生命周期
    useEffect(() => {
        fetchCourses();
    }, [JSON.stringify(page)]);
    // 初始化方法
    const fetchCourses = () => {
        const info = {
            pageNum: page.pageNum,
            pageSize: page.pageSize,
            range: page.range,
            refMajors: page.refMajors,
            required: page.required,
            name: page.name
        };
        searchCourse(info)
            .then((res) => {
                setCourses(res.data)
            })
            .catch((e) => {
                console.log(e);
            });
    };

    // 搜索框方法
    const search = (value) => {
        setSelectedItem("课程")
        page.name = value
        setPage(page)
        handleItemClick("课程", page)
        // fetchCourses()

    }
    // 点击查查后出现列表
    const style = {
        display: 'flex' as const,
        width: 300,
        height: 30,
        marginBottom: 20,
    };
    const styleItem = {
        flex: 1,
        textAlign: 'center' as const,
        cursor: 'pointer',
        height: 30,
        lineHeight: '30px',
        borderRadius: '30px',
    };
    const [selectedItem, setSelectedItem] = useState(null);
    const handleItemClick = (item, pages) => {
        console.log(pages, "page")
        setSelectedItem(item);

        if (item == '课程') {
            const data = {
                pageNum: pages.pageNum,
                pageSize: pages.pageSize,
                name: pages.name
            }
            getLessonsByPageApi(data).then(res => {
                // const updatedData = [];
                setLeftMenu([]);
                setCourses(res.data)
                //   fetchCourses()
            })
        }
        if (item == '章节') {
            const data = {
                pageNum: pages.pageNum,
                pageSize: pages.pageSize,
                name: pages.name
            }
            // newArray[0] = param
            setLeftMenu(["1"])
            searchCourseChapter(data).then(res => {
                setCourses(res.data)
                //   fetchCourses()
            })
        }
        if (item == '知识') {
            const data = {
                pageNum: pages.pageNum,
                pageSize: pages.pageSize,
                name: pages.name
            }
            searchCourseKnowledge(data).then(res => {
                setLeftMenu(["1", "2"],)
                setCourses(res.data)
                //   fetchCourses()
            })
        }
        if (item == '资料') {
            const data = {
                pageNum: pages.pageNum,
                pageSize: pages.pageSize,
                name: pages.name
            }
            searchCourseResource(data).then(res => {
                setLeftMenu(["1", "2", "3"],)
                setCourses(res.data)
                //   fetchCourses()
            })
        }
    };
    const ShowMenus = () => {
        if (
            selectedItem !== '课程' &&
            selectedItem !== '章节' &&
            selectedItem !== '知识' &&
            selectedItem !== '资料'
        ) {
            return null;
        }
        return (
            <div style={style} >
                <div
                    style={{
                        ...styleItem,
                        backgroundColor: selectedItem === '课程' ? '#F2F3F5' : 'transparent',
                        color: selectedItem === '课程' ? 'blue' : 'black',
                    }}
                    onClick={() => handleItemClick('课程', page)}
                >
                    课程
                </div>
                <div
                    style={{
                        ...styleItem,
                        backgroundColor: selectedItem === '章节' ? '#F2F3F5' : 'transparent',
                        color: selectedItem === '章节' ? 'blue' : 'black',
                    }}
                    onClick={() => handleItemClick('章节', page)}
                >
                    章节
                </div>
                <div
                    style={{
                        ...styleItem,
                        backgroundColor: selectedItem === '知识' ? '#F2F3F5' : 'transparent',
                        color: selectedItem === '知识' ? 'blue' : 'black',
                    }}
                    onClick={() => handleItemClick('知识', page)}
                >
                    知识
                </div>
                <div
                    style={{
                        ...styleItem,
                        backgroundColor: selectedItem === '资料' ? '#F2F3F5' : 'transparent',
                        color: selectedItem === '资料' ? 'blue' : 'black',
                    }}
                    onClick={() => handleItemClick('资料', page)}
                >
                    资料
                </div>
            </div>
        );
    };
    // 分页方法
    const sizeCanChange = (pageNumber, pageSize) => {
        page.pageNum = pageNumber
        page.pageSize = pageSize
        const updatedData = [];
        setLeftMenu(updatedData);
        fetchCourses()
    }
    // 重置分页信息搜索条件
    const resetPagination = () => {
        Object.assign(page, initPage)
    }

    const [selectedSpan, setSelectedSpan] = useState(null);
    const [selectedSpan1, setSelectedSpan1] = useState(null);
    const [selectedSpan2, setSelectedSpan2] = useState(null);

    // 点击重置
    const resetting = () => {
        page.range = ""
        page.refMajors = ""
        page.required = ""
        setSelectedSpan("");
        setSelectedSpan1("");
        setSelectedSpan2("");
        page.name = ""
        setPage(page)
        setInputValue('');
        const updatedData = [];
        setLeftMenu(updatedData);
        setSelectedItem("未知")
        fetchCourses()
    }
    // 点击范围搜索
    const handleSpanClick = (index) => {
        setSelectedSpan(index);
        if (index == 0) {
            page.range = ""
        } else {
            page.range = index - 1 + ""
        }
        // fetchCourses()
    };
    //点击相关专业搜索
    const handleSpanClick1 = (index) => {
        setSelectedSpan1(index);
        if (index == 0) {
            page.refMajors = ""
        }
        if (index == 1) {
            page.refMajors = index - 1 + ""
        }
        if (index == 2) {
            page.refMajors = index - 1 + ""
        }
        // fetchCourses()
    };
    // 点击是否必修课搜索
    const handleSpanClick2 = (index) => {
        setSelectedSpan2(index);
        if (index == 0) {
            page.required = ""
        }
        if (index == 1) {
            page.required = index - 1 + ""
        }
        if (index == 2) {
            page.required = index - 1 + ""
        }
        console.log(page, "是否必修")
        // fetchCourses()
    };
    // 点击查询
    const seachAll = () => {
        // console.log(selectedSpan2,"page")
        page.range = selectedSpan
        page.required = selectedSpan2
        page.refMajors = selectedSpan1
        fetchCourses()
    }
    // 点击出现弹窗
    const openMenu = (record) => {
        detailRef.current.setInfo({
            schCourseId: record.schCourseId || record.id,
            bizType: record.bizType||leftMenu.length,
            id: record.id,
            name:record.name
        })
        detailRef.current.setVisible(true);
    }
    // 课程列表
    const renderItems = () => {
        const items = [];
        for (let i = 0; i < courses.list.length; i++) {
            items.push(<div key={i} className={styles.item}  >
                <img src={require('../img/Vector.png')} className={styles.icon} alt="" onClick={(event) => itemClick(event, courses.list[i])} />
                <div onClick={() => openMenu(courses.list[i])} >
                    <div className={styles.title}>
                        <span> <img className={styles.img} src={require('../img/book.png')} alt="" /> </span>
                        <span>{courses.list[i].name} </span>
                    </div>
                    <div className={styles.content}>
                        {/* <div >
                        {courses.list[i].introduce}
                    </div> */}
                        <div>
                            <div>
                                <div className={styles.number}>
                                    {courses.list[i].countMsg && courses.list[i].countMsg.chapterNum}
                                </div>
                                <div>
                                    章节
                                </div>
                            </div>
                            <div>
                                <div className={styles.number}>
                                    {courses.list[i].countMsg && courses.list[i].countMsg.knowledgeNum}
                                </div>
                                <div>
                                    知识
                                </div>
                            </div>
                            <div>
                                <div className={styles.number}>
                                    {courses.list[i].countMsg && courses.list[i].countMsg.resourceNum}
                                </div>
                                <div>
                                    资料
                                </div>
                            </div>
                            {/* <div>
                            <div className={styles.number}>
                                451
                            </div>
                            <div>
                                课中学生人数
                            </div>
                        </div> */}
                        </div>
                    </div>
                </div>  {/* <IconRightCircle className={styles.icon} style={{ fontSize: 42, strokeLinecap: 'square', strokeWidth: 5 }} /> */}

            </div>);
        }

        return items;
    };
    // 快捷搜索列表
    const searchList = () => {
        return <div>
            <div className={styles.mainBox}>
                <div>
                    <div className={styles.main1box}>
                        <p className={styles.p1}>范围</p>
                        <p className={styles.p2}> <span
                            className={selectedSpan === 0 ? styles.blue : styles.gray}
                            onClick={() => handleSpanClick(0)}
                        >
                            全部 </span>
                            <span
                                className={selectedSpan === 1 ? styles.blue : styles.gray}
                                onClick={() => handleSpanClick(1)}
                            >我负责的</span> </p>
                    </div>
                    <div className={styles.main1box}>
                        <p className={styles.p1}>相关专业</p>
                        <p className={styles.p2}> <span
                            className={selectedSpan1 === 0 ? styles.blue : styles.gray}
                            onClick={() => handleSpanClick1(0)}
                        > 全部 </span> <span
                            className={selectedSpan1 === 1 ? styles.blue : styles.gray}
                            onClick={() => handleSpanClick1(1)}
                        >我的专业</span> <span
                            className={selectedSpan1 === 2 ? styles.blue : styles.gray}
                            onClick={() => handleSpanClick1(2)}
                        >公开课</span> </p>
                    </div>
                    <div className={styles.main1box}>
                        <p className={styles.p1}>是否必修课</p>
                        <p className={styles.p2}> <span
                            className={selectedSpan2 === 0 ? styles.blue : styles.gray}
                            onClick={() => handleSpanClick2(0)}
                        > 全部 </span>
                            <span
                                className={selectedSpan2 === 1 ? styles.blue : styles.gray}
                                onClick={() => handleSpanClick2(1)}
                            >是</span> <span
                                className={selectedSpan2 === 2 ? styles.blue : styles.gray}
                                onClick={() => handleSpanClick2(2)}
                            >否</span> </p>
                    </div>
                </div>
            </div>
        </div>


    }
    //抽屉

    // 点击课程列表
    const itemClick = (event, record) => {
        // if (selectedItem == "课程" || selectedItem == "章节" || selectedItem == "知识" || selectedItem == "资料") {
        //     return
        // }
        event.stopPropagation()
        const param = {
            id: record.id,
            name: record.name,
            introduce: record.introduce
        }
        //点击课程列表替换菜单数组中第一列数组
        const newArray = [...leftMenu];
        newArray[0] = param

        console.log(newArray,'newArrayv')
        setLeftMenu(newArray)
        resetPagination()
        const info = {
            pageNum: page.pageNum,
            pageSize: page.pageSize,
            schCourseId: record.id
        };
        getChapterBySchCourseId(info).then(res => {
            setCourses(res.data)
        }).catch(e => {
            console.log(e)
        })





    }
    // 二级页面
    const levelItem = () => {
        //左侧卡片渲染逻辑
        function item() {
            // 删除卡片内容
            function delMenu(index) {
                //如果数组长度为1
                if (leftMenu.length === 1) {
                    setLeftMenu([])
                } else {
                    //如果删除前置菜单则移除子项所有菜单
                    const updatedData = leftMenu.slice(0, index);
                    setLeftMenu(updatedData);
                }
                let info = {}
                switch (index) {
                    case 0:
                        fetchCourses()
                        break
                    case 1:
                        resetPagination()
                        info = {
                            pageNum: page.pageNum,
                            pageSize: page.pageSize,
                            schCourseId: leftMenu[index - 1].id
                        };
                        getChapterBySchCourseId(info).then(res => {
                            setCourses(res.data)
                        }).catch(e => {
                            console.log(e)
                        })
                        break
                    default:
                        resetPagination()
                        info = {
                            pageNum: page.pageNum,
                            pageSize: page.pageSize,
                            schCourseChapterId: leftMenu[index - 1].id
                        };
                        getSchCourseKnowledgeBySchCourseChapterId(info).then(res => {
                            setCourses(res.data)
                        })
                }

            }
            // 123
            const item = leftMenu.map((item, index) => {
                // if (selectedItem !== "课程" && selectedItem !== "章节" && selectedItem !== "知识" && selectedItem !== "资料") {
                    return (
                        <div className={styles.menuLeft} key={index}>
                            <div className={styles.leftItem}>
                                <div>
                                    <img className={styles.imgs} src={require('../img/book.png')} alt="" />
                                </div>
                                <div>{item.name}</div>
                                <IconCloseCircle
                                    className={styles.icon}
                                    style={{ fontSize: 20, strokeLinecap: 'square', strokeWidth: 3 }}
                                    onClick={() => delMenu(index)}
                                />
                            </div>
                            {leftMenu[index + 1] !== undefined && (
                                <div className={styles.lineDiv}>
                                    <div className={styles.line}></div>
                                </div>
                            )}
                        </div>
                    );
                // } else {
                //     return null; // 返回 null 来隐藏菜单项
                // }

            });
            return item
        }

        // 二级列表渲染逻辑
        function list() {
            let show = true
            if (leftMenu.length >= 3) {
                show = false
            } else {
                show = true
            }
            // 时间格式化方法
            function formatDate(dateString) {
                const date = new Date(dateString);
                const month = date.getMonth() + 1;
                const day = date.getDate();
                return `${month}/${day}`;
            }

            // 二级列表点击逻辑


            function AdMenu(record) {

                // alert("!")
                const newArray = [...leftMenu];
                const param = {
                    id: record.id,
                    name: record.name,
                    introduce: record.introduce
                }
                //点击永远只向下点击除了最后一个元素so只替换数组长度的位置即可
                newArray[leftMenu.length] = param
                resetPagination()
                //2 3都为知识点走一个逻辑即可 4填满了走弹窗逻辑
                if (newArray.length > 4) {


                } else if (newArray.length === 4) {
                    setLeftMenu(newArray)
                    const info = {
                        pageNum: page.pageNum,
                        pageSize: page.pageSize,
                        schCourseKnowledgeId: record.id
                    };
                    getSchCourseResourceBySchCourseKnowledgeId(info).then(res => {
                        setCourses(res.data)
                    })
                } else {
                    setLeftMenu(newArray)
                    const info = {
                        pageNum: page.pageNum,
                        pageSize: page.pageSize,
                        schCourseChapterId: record.id
                    };
                    getSchCourseKnowledgeBySchCourseChapterId(info).then(res => {
                        setCourses(res.data)
                    })
                }




            }

            const menu = ['章节', '知识点', '二级知识点', '资源']


            // 渲染
            const pageList = courses.list.map((item, index) => {
                return <div className={styles.center} key={index} >
                    <div className={styles.centerItem} >
                        {/* {leftMenu.length} */}
                        {show ? <img src={require('../img/Vector.png')} onClick={() => AdMenu(item)} className={styles.icon} alt="" /> : <img />}

                        <div onClick={() => openMenu(item)}>
                            <div>
                                <img className={styles.img2} src={require('../img/book.png')} alt="" />
                                <Tag color='#E9F3FF' bordered  >{menu[leftMenu.length-1]}</Tag>
                                <div >{item.name}</div>
                            </div>
                            <div>
                                <div>更新时间：{formatDate(item.updateTime)}</div>
                                <div>|</div>
                                <div>知识量：{item.countMsg.knowledgeNum}</div>
                            </div>
                        </div>
                    </div>
                </div>
            })

            return pageList
        }

        //左侧上小标题

        function leftTitle() {


            const menu = ['课程', '章节', '知识点'];

            const title = leftMenu.map((_, i) => {
                if (i === leftMenu.length - 1 || i >= menu.length) {
                    return <div key={i} className={styles.title}>{menu[i]}</div>;
                } else {
                    return (
                        <div key={i} className={styles.title}>
                            {menu[i]}-
                        </div>
                    );
                }
            });



            return title
        }
        // 中间上面标题
        function centerTitle() {
            const menu = ['章节', '知识点', '二级知识点', '资源']

            // return <div className={styles.title}>{menu[leftMenu.length-1]}</div>
        }




        const shouldShowRow = selectedItem !== "课程" && selectedItem !== "章节" && selectedItem !== "知识" && selectedItem !== "资料";
        return <div>
            <Row>
               
                <Col span={shouldShowRow? 6:0} >
                    {item()}
                </Col>

                <Col span={18}>
                    <div className={styles.centerT}>
                        {centerTitle()}
                        {list()}
                    </div>

                </Col>

            </Row>

        </div>






    }
    // 是否展示子页面menuLeft数组元素第一个为null则为主页
    const showMenu = () => {

        if (!!leftMenu[0]) return <div>
            {/*{courses.list.length === 0 ?*/}
            {/*    <div style={{*/}
            {/*        display: 'flex', flexDirection: 'column', alignItems: 'center',*/}
            {/*        justifyContent: 'center', height: '100vh'*/}
            {/*    }}><Empty /></div>*/}
            {/*    : <div>{levelItem()} </div>}*/}

            <div>{levelItem()} </div>
        </div>
        else return (
            <div>
                {/*{courses.list.length === 0 ?*/}
                {/*    <div style={{*/}
                {/*        display: 'flex', flexDirection: 'column', alignItems: 'center',*/}
                {/*        justifyContent: 'center', height: '100vh'*/}
                {/*    }}><Empty /></div>*/}
                {/*    : <div className={styles.itemParent} >{renderItems()} </div>}*/}

                <div className={styles.itemParent} >{renderItems()} </div>
            </div>

        );


    }
    const shouldShowRow = selectedItem !== "课程" && selectedItem !== "章节" && selectedItem !== "知识" && selectedItem !== "资料";
    return (

        <Card className={styles.container}>
            <div className={styles.search}>
                <div className={styles.text}> 搜索一下 </div>
                <InputSearch
                    value={inputValue}
                    onChange={(e) => setInputValue(e)}
                    placeholder='请输入你要查找的信息'
                    searchButton='查 查'
                    style={{ width: '65%', margin: 0, height: '30px' }}
                    size={"large"}
                    height={'40px'}
                    onSearch={search}
                />

            </div>

            <Row>
                
                <Col span={18} className={styles.boxheight}>
                {/* <div>{shouldShowRow}</div> */}
                    <div>{ShowMenus()}</div>
                    <div>{showMenu()}</div>

                </Col>
                <Col span={6}>
                    <div className={`${styles.title} ${styles.mainBox}`} style={{ marginTop: "-60px", height: "40px", lineHeight: "44px" }}>快速筛选</div>
                    <div style={{ marginLeft: "100px", marginTop: '20px' }} >
                        <Button type='primary' onClick={seachAll} size='large' icon={<IconSearch />}>
                            查询
                        </Button>
                        <Button type='outline' size='large' onClick={resetting} icon={<IconLoop />}>
                            重置
                        </Button>
                    </div>

                    {searchList()}
                </Col>
            </Row>
            <Pagination showTotal showJumper onChange={(pageNumber, pageSize) => sizeCanChange(pageNumber, pageSize)} pageSize={page.pageSize} className={styles.page} total={courses.total} />
            <DetailDrawer ref={detailRef} openMenu={openMenu} />
        </Card>




    )

}


export default KnowledgeCheck
